<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'

const AMAP_KEY = 'd93428c62f0f8fcbcbe1be9e05893e41' // 你的高德Key
const mapError = ref(false)
const map = ref(null)
const searchKeyword = ref('')
const searchResults = ref([])
const showSearchResults = ref(false)
const isMeasuring = ref(false)
const measurePoints = ref([])
const customMarkers = ref([])
const showMarkerForm = ref(false)
const newMarker = ref({
  name: '',
  description: '',
  type: 'custom'
})

// 货车动态路线相关变量
const truckMarker = ref(null)
const truckPath = ref(null)
const truckAnimation = ref(null)
const isTruckMoving = ref(false)

// 新增：配送进度信息
const currentStationIndex = ref(0)
const nextStationName = ref('')
const estimatedDistance = ref(0)
const estimatedTime = ref(0)

// 新增：全程真实路线点
const fullRoutePoints = ref([])

// 新增：当前地区名
const currentLocationName = ref('')

// 预设的配送路线（从北京到昆明）
const deliveryRoute = [
  [116.397428, 39.90923],    // 北京
  [117.190182, 39.125596],   // 天津
  [113.264435, 23.129163],   // 广州
  [102.832891, 24.880095]    // 昆明
]

// 站点数据
const stations = [
  {
    name: '北京主仓库',
    position: [116.397428, 39.90923],
    icon: '🏭',
    type: '仓库'
  },
  {
    name: '上海配送中心',
    position: [121.473658, 31.230378],
    icon: '🚚',
    type: '配送中心'
  },
  {
    name: '广州物流园',
    position: [113.264435, 23.129163],
    icon: '📦',
    type: '物流园',
    specialGoods: [
      { type: '服装', icon: '👕' },
      { type: '电子产品', icon: '📱' }
    ]
  },
  {
    name: '深圳转运站',
    position: [114.057868, 22.543099],
    icon: '🔄',
    type: '转运站'
  },
  {
    name: '杭州配送点',
    position: [120.155070, 30.274084],
    icon: '📍',
    type: '配送点'
  },
  {
    name: '成都仓储中心',
    position: [104.065735, 30.659462],
    icon: '🏭',
    type: '仓库'
  },
  {
    name: '重庆配送站',
    position: [106.551556, 29.563009],
    icon: '🚚',
    type: '配送中心'
  },
  {
    name: '南京物流基地',
    position: [118.796877, 32.060255],
    icon: '📦',
    type: '物流园'
  },
  {
    name: '武汉转运中心',
    position: [114.298572, 30.584355],
    icon: '🔄',
    type: '转运站'
  },
  {
    name: '西安配送点',
    position: [108.948024, 34.263161],
    icon: '📍',
    type: '配送点'
  },
  {
    name: '天津仓库',
    position: [117.190182, 39.125596],
    icon: '🏭',
    type: '仓库'
  },
  {
    name: '青岛配送中心',
    position: [120.369557, 36.094406],
    icon: '🚚',
    type: '配送中心'
  },
  {
    name: '大连物流园',
    position: [121.618622, 38.914589],
    icon: '📦',
    type: '物流园'
  },
  {
    name: '厦门转运站',
    position: [118.089425, 24.479834],
    icon: '🔄',
    type: '转运站'
  },
  {
    name: '苏州配送点',
    position: [120.619585, 31.299379],
    icon: '📍',
    type: '配送点'
  },
  {
    name: '无锡仓储中心',
    position: [120.31191, 31.491169],
    icon: '🏭',
    type: '仓库'
  },
  {
    name: '宁波配送站',
    position: [121.549792, 29.868388],
    icon: '🚚',
    type: '配送中心'
  },
  {
    name: '长沙物流基地',
    position: [112.938814, 28.228209],
    icon: '📦',
    type: '物流园'
  },
  {
    name: '郑州转运中心',
    position: [113.665412, 34.757975],
    icon: '🔄',
    type: '转运站'
  },
  {
    name: '合肥配送点',
    position: [117.227219, 31.820591],
    icon: '📍',
    type: '配送点'
  },
  {
    name: '迈阿密拉美贸易中转站',
    position: [-80.191790, 25.761680],
    icon: '🌎',
    type: '拉美贸易中转站',
    specialGoods: [
      { type: '水果', icon: '🍊' },
      { type: '药品', icon: '💊' }
    ]
  },
  {
    name: '孟菲斯联邦快递全球枢纽',
    position: [-89.971130, 35.149530],
    icon: '✈️',
    type: '联邦快递全球枢纽',
    specialGoods: [
      { type: '医疗器械', icon: '🏥' }
    ]
  },
  {
    name: '阿姆斯特丹史基浦机场',
    position: [4.763889, 52.308613],
    icon: '🛫',
    type: '欧洲第四大货运机场',
    specialGoods: [
      { type: '鲜花', icon: '🌷' },
      { type: '芯片运输', icon: '🔌' }
    ]
  },
  {
    name: '西班牙瓦伦西亚地中海贸易枢纽',
    position: [-0.376288, 39.469907],
    icon: '🚢',
    type: '地中海贸易枢纽',
    specialGoods: [
      { type: '汽车', icon: '🚗' }
    ]
  }
]

// 检查API密钥是否有效
function checkAPIKey() {
  console.log('当前API密钥:', AMAP_KEY)
  console.log('密钥长度:', AMAP_KEY.length)
  
  if (!AMAP_KEY || AMAP_KEY.length < 20) {
    ElMessage.error('API密钥无效，请检查配置')
    return false
  }
  
  return true
}

// 简单搜索测试
function simpleSearchTest() {
  if (!checkAPIKey()) return
  
  // 使用用户输入的关键词，如果没有输入则使用默认值
  const keyword = searchKeyword.value.trim() || '北京天安门'
  
  console.log('开始API搜索测试，关键词:', keyword)
  
  // 直接使用fetch测试API
  const testUrl = `https://restapi.amap.com/v3/place/text?key=${AMAP_KEY}&keywords=${encodeURIComponent(keyword)}&city=全国&output=json&offset=10&page=1`
  
  fetch(testUrl)
    .then(response => response.json())
    .then(data => {
      console.log('API测试结果:', data)
      if (data.status === '1') {
        ElMessage.success('API连接正常，找到 ' + (data.pois?.length || 0) + ' 个结果')
        
        // 将结果转换为搜索结果显示格式
        if (data.pois && data.pois.length > 0) {
          const pois = data.pois.map((poi, index) => ({
            id: `api_${index}`,
            name: poi.name,
            address: poi.address || poi.pname + poi.cityname + poi.adname,
            location: {
              lng: parseFloat(poi.location.split(',')[0]),
              lat: parseFloat(poi.location.split(',')[1])
            },
            type: poi.type || '地点'
          }))
          
          searchResults.value = pois
          showSearchResults.value = true
        } else {
          ElMessage.warning('未找到相关地点')
          searchResults.value = []
          showSearchResults.value = false
        }
      } else {
        ElMessage.error('API返回错误: ' + (data.info || '未知错误'))
      }
    })
    .catch(error => {
      console.error('API测试失败:', error)
      ElMessage.error('网络连接失败: ' + error.message)
    })
}

// 使用API直接搜索（替代JavaScript SDK搜索）
function apiSearch() {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  if (!checkAPIKey()) return
  
  const keyword = searchKeyword.value.trim()
  console.log('开始API搜索:', keyword)
  
  // 显示加载状态
  ElMessage.info('正在搜索...')
  
  const searchUrl = `https://restapi.amap.com/v3/place/text?key=${AMAP_KEY}&keywords=${encodeURIComponent(keyword)}&city=全国&output=json&offset=20&page=1&extensions=all`
  
  fetch(searchUrl)
    .then(response => response.json())
    .then(data => {
      console.log('API搜索结果:', data)
      if (data.status === '1') {
        if (data.pois && data.pois.length > 0) {
          const pois = data.pois.map((poi, index) => ({
            id: `api_${index}`,
            name: poi.name,
            address: poi.address || poi.pname + poi.cityname + poi.adname,
            location: {
              lng: parseFloat(poi.location.split(',')[0]),
              lat: parseFloat(poi.location.split(',')[1])
            },
            type: poi.type || '地点',
            tel: poi.tel || '',
            distance: poi.distance || ''
          }))
          
          searchResults.value = pois
          showSearchResults.value = true
          ElMessage.success(`找到 ${pois.length} 个结果`)
        } else {
          ElMessage.warning('未找到相关地点，请尝试其他关键词')
          searchResults.value = []
          showSearchResults.value = false
        }
      } else {
        ElMessage.error('搜索失败: ' + (data.info || '未知错误'))
        searchResults.value = []
        showSearchResults.value = false
      }
    })
    .catch(error => {
      console.error('API搜索失败:', error)
      ElMessage.error('网络连接失败: ' + error.message)
      searchResults.value = []
      showSearchResults.value = false
    })
}

function loadAMapScript() {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve(window.AMap)
      return
    }
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}&plugin=AMap.Geolocation,AMap.Scale,AMap.ToolBar`
    script.onload = () => {
      console.log('高德地图API加载成功')
      resolve(window.AMap)
    }
    script.onerror = (error) => {
      console.error('高德地图API加载失败:', error)
      reject(error)
    }
    document.head.appendChild(script)
  })
}

// 添加站点标记
function addStationMarkers() {
  stations.forEach(station => {
    // 为有特殊商品的站点创建多图标显示
    if (station.specialGoods && station.specialGoods.length > 0) {
      // 创建多个小图标标记
      station.specialGoods.forEach((good, index) => {
        const offsetX = index === 0 ? -25 : 5 // 第一个图标偏左，第二个偏右
        const offsetY = index === 0 ? -15 : -15
        
        const textMarker = new window.AMap.Text({
          text: good.icon,
          position: station.position,
          style: {
            'font-size': '20px',
            'font-weight': 'bold',
            'color': '#0369a1',
            'background-color': 'white',
            'border-radius': '50%',
            'border': '2px solid #0369a1',
            'padding': '6px',
            'box-shadow': '0 2px 8px rgba(0,0,0,0.2)'
          },
          offset: new window.AMap.Pixel(offsetX, offsetY)
        })

        // 添加点击事件
        textMarker.on('click', () => {
          showStationInfo(station)
        })

        // 添加到地图
        textMarker.setMap(map.value)
      })
    } else {
      // 其他站点使用原来的单图标显示
      const textMarker = new window.AMap.Text({
        text: station.icon,
        position: station.position,
        style: {
          'font-size': '24px',
          'font-weight': 'bold',
          'color': '#409eff',
          'background-color': 'white',
          'border-radius': '50%',
          'border': '2px solid #409eff',
          'padding': '4px',
          'box-shadow': '0 2px 8px rgba(0,0,0,0.2)'
        },
        offset: new window.AMap.Pixel(-15, -15)
      })

      // 添加点击事件
      textMarker.on('click', () => {
        showStationInfo(station)
      })

      // 添加到地图
      textMarker.setMap(map.value)
    }
  })
}

// 显示站点信息
function showStationInfo(station) {
  // 生成特殊商品图标HTML
  let specialGoodsHTML = ''
  if (station.specialGoods && station.specialGoods.length > 0) {
    specialGoodsHTML = `
      <div style="border-top: 1px solid #f0f0f0; padding-top: 10px; margin-top: 10px;">
        <p style="margin: 5px 0; color: #666; font-size: 13px;">
          <strong>特殊商品:</strong>
        </p>
        <div style="display: flex; gap: 8px; margin-top: 5px;">
          ${station.specialGoods.map(good => `
            <span style="display: flex; align-items: center; gap: 4px; background: #f0f9ff; color: #0369a1; padding: 4px 8px; border-radius: 12px; font-size: 12px; border: 1px solid #bae6fd;">
              <span style="font-size: 14px;">${good.icon}</span>
              <span>${good.type}</span>
            </span>
          `).join('')}
        </div>
      </div>
    `
  }

  const infoWindow = new window.AMap.InfoWindow({
    content: `
      <div style="padding: 15px; min-width: 250px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 12px;">
          <span style="font-size: 24px;">${station.icon}</span>
          <div>
            <h3 style="margin: 0; color: #409eff; font-size: 16px;">${station.name}</h3>
            <span style="background: #e6f7ff; color: #1890ff; padding: 2px 8px; border-radius: 10px; font-size: 12px;">${station.type}</span>
          </div>
        </div>
        <div style="border-top: 1px solid #f0f0f0; padding-top: 10px;">
          <p style="margin: 5px 0; color: #666; font-size: 13px;">
            <strong>位置:</strong> ${station.position.join(', ')}
          </p>
          <p style="margin: 5px 0; color: #666; font-size: 13px;">
            <strong>类型:</strong> ${station.type}
          </p>
        </div>
        ${specialGoodsHTML}
      </div>
    `,
    offset: new window.AMap.Pixel(0, -30)
  })
  
  infoWindow.open(map.value, station.position)
}

// 选择搜索结果
function selectSearchResult(place) {
  try {
    console.log('选择地点:', place)
    
    if (!place.location) {
      ElMessage.error('地点位置信息不完整')
      return
    }
    
    const position = [place.location.lng, place.location.lat]
    console.log('定位到:', position)
    
    map.value.setCenter(position)
    map.value.setZoom(15)
    
    // 添加标记
    const marker = new window.AMap.Marker({
      position: position,
      title: place.name,
      icon: new window.AMap.Icon({
        size: [32, 32],
        image: '',
        imageSize: [32, 32]
      })
    })

    marker.setMap(map.value)
    
    // 显示信息窗口
    const infoWindow = new window.AMap.InfoWindow({
      content: `
        <div style="padding: 15px; min-width: 250px;">
          <h3 style="margin: 0 0 10px 0; color: #f56c6c;">${place.name}</h3>
          <p style="margin: 5px 0; color: #666;">地址: ${place.address || '未知'}</p>
          <p style="margin: 5px 0; color: #666;">类型: ${place.type || '未知'}</p>
          <p style="margin: 5px 0; color: #666;">坐标: ${position.join(', ')}</p>
        </div>
      `,
      offset: new window.AMap.Pixel(0, -30)
    })
    
    infoWindow.open(map.value, position)
    showSearchResults.value = false
    searchKeyword.value = ''
    
    ElMessage.success('已定位到: ' + place.name)
  } catch (error) {
    console.error('选择地点失败:', error)
    ElMessage.error('定位失败: ' + error.message)
  }
}

// 获取当前位置
function getCurrentLocation() {
  const geolocation = new window.AMap.Geolocation({
    enableHighAccuracy: true,
    timeout: 10000,
    buttonPosition: 'RB',
    buttonOffset: new window.AMap.Pixel(10, 20),
    zoomToAccuracy: true
  })

  map.value.addControl(geolocation)

  geolocation.getCurrentPosition((status, result) => {
    if (status === 'complete') {
      const position = [result.position.lng, result.position.lat]
      map.value.setCenter(position)
      map.value.setZoom(15)
      
      ElMessage.success('定位成功')
      
      // 添加当前位置标记
      const marker = new window.AMap.Marker({
        position: position,
        title: '当前位置',
        icon: new window.AMap.Icon({
          size: [32, 32],
          image: '',
          imageSize: [32, 32]
        })
      })

      marker.setMap(map.value)
    } else {
      ElMessage.error('定位失败，请检查定位权限')
    }
  })
}

// 开始测距
function startMeasuring() {
  isMeasuring.value = true
  measurePoints.value = []
  
  map.value.on('click', handleMapClick)
  ElMessage.info('点击地图开始测距，再次点击结束测距')
}

// 处理地图点击
function handleMapClick(e) {
  if (!isMeasuring.value) return
  
  const position = [e.lnglat.lng, e.lnglat.lat]
  measurePoints.value.push(position)
  
  // 添加测距点标记
  const marker = new window.AMap.Marker({
    position: position,
    title: `测距点${measurePoints.value.length}`,
    icon: new window.AMap.Icon({
      size: [24, 24],
      image: '',
      imageSize: [24, 24]
    })
  })

  marker.setMap(map.value)
  
  if (measurePoints.value.length >= 2) {
    // 绘制测距线
    const polyline = new window.AMap.Polyline({
      path: measurePoints.value,
      strokeColor: '#E6A23C',
      strokeWeight: 3,
      strokeStyle: 'dashed'
    })
    
    polyline.setMap(map.value)
    
    // 计算距离
    const distance = calculateDistance(measurePoints.value[0], measurePoints.value[1])
    ElMessage.success(`距离: ${distance.toFixed(2)} 公里`)
    
    // 结束测距
    isMeasuring.value = false
    map.value.off('click', handleMapClick)
  }
}

// 计算距离
function calculateDistance(point1, point2) {
  const R = 6371 // 地球半径（公里）
  const dLat = (point2[1] - point1[1]) * Math.PI / 180
  const dLon = (point2[0] - point1[0]) * Math.PI / 180
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(point1[1] * Math.PI / 180) * Math.cos(point2[1] * Math.PI / 180) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  return R * c
}

// 清除测距
function clearMeasuring() {
  isMeasuring.value = false
  measurePoints.value = []
  map.value.off('click', handleMapClick)
  
  // 清除地图上的标记和线条
  map.value.clearMap()
  addStationMarkers()
  
  ElMessage.success('已清除测距')
}

// 添加自定义标记
function addCustomMarker() {
  showMarkerForm.value = true
}

// 确认添加标记
function confirmAddMarker() {
  if (!newMarker.value.name.trim()) {
    ElMessage.warning('请输入标记名称')
    return
  }
  
  // 这里可以获取地图中心点或让用户点击选择位置
  const center = map.value.getCenter()
  const position = [center.lng, center.lat]
  
  const marker = {
    name: newMarker.value.name,
    description: newMarker.value.description,
    position: position,
    type: 'custom'
  }
  
  customMarkers.value.push(marker)
  
  // 添加标记到地图
  const mapMarker = new window.AMap.Marker({
    position: position,
    title: marker.name,
    icon: new window.AMap.Icon({
      size: [28, 28],
      image: '',
      imageSize: [28, 28]
    })
  })

  mapMarker.on('click', () => {
    showCustomMarkerInfo(marker)
  })

  mapMarker.setMap(map.value)
  
  // 重置表单
  newMarker.value = { name: '', description: '', type: 'custom' }
  showMarkerForm.value = false
  
  ElMessage.success('自定义标记添加成功')
}

// 显示自定义标记信息
function showCustomMarkerInfo(marker) {
  const infoWindow = new window.AMap.InfoWindow({
    content: `
      <div style="padding: 15px; min-width: 250px;">
        <h3 style="margin: 0 0 10px 0; color: #909399;">${marker.name}</h3>
        <p style="margin: 5px 0; color: #666;">描述: ${marker.description || '无'}</p>
        <p style="margin: 5px 0; color: #666;">位置: ${marker.position.join(', ')}</p>
        <p style="margin: 5px 0; color: #666;">类型: 自定义标记</p>
      </div>
    `,
    offset: new window.AMap.Pixel(0, -30)
  })
  
  infoWindow.open(map.value, marker.position)
}

// 获取两点间真实路线
async function getRoutePoints(origin, destination) {
  const url = `https://restapi.amap.com/v3/direction/driving?origin=${origin[0]},${origin[1]}&destination=${destination[0]},${destination[1]}&key=${AMAP_KEY}`
  const res = await fetch(url)
  const data = await res.json()
  if (data.status === '1' && data.route.paths.length > 0) {
    let points = []
    data.route.paths[0].steps.forEach(step => {
      points = points.concat(step.polyline.split(';').map(str => str.split(',').map(Number)))
    })
    return points
  }
  return []
}

// 获取全程路线
async function getFullRoutePoints() {
  let allPoints = []
  for (let i = 0; i < deliveryRoute.length - 1; i++) {
    const seg = await getRoutePoints(deliveryRoute[i], deliveryRoute[i+1])
    if (i > 0 && seg.length > 0) seg.shift() // 避免重复
    allPoints = allPoints.concat(seg)
  }
  return allPoints
}

function updateTruckInfo(currentIndex) {
  // 当前站点是currentIndex，下一站是currentIndex+1
  if (currentIndex < deliveryRoute.length - 1) {
    // 查找站点名
    const start = deliveryRoute[currentIndex]
    const end = deliveryRoute[currentIndex + 1]
    const nextStation = stations.find(s => s.position[0] === end[0] && s.position[1] === end[1])
    nextStationName.value = nextStation ? nextStation.name : `第${currentIndex + 2}站`
    // 计算距离
    estimatedDistance.value = calculateDistance(start, end)
    // 预计时间（假设平均速度60km/h）
    estimatedTime.value = estimatedDistance.value / 60
  } else {
    nextStationName.value = '已到达终点'
    estimatedDistance.value = 0
    estimatedTime.value = 0
  }
}

// 沿真实路线动画
async function startTruckDelivery() {
  if (isTruckMoving.value) {
    ElMessage.warning('货车正在配送中...')
    return
  }
  isTruckMoving.value = true
  // 获取全程真实路线点
  fullRoutePoints.value = await getFullRoutePoints()
  if (!fullRoutePoints.value.length) {
    ElMessage.error('未能获取真实路线')
    isTruckMoving.value = false
    return
  }
  // 画实线
  if (truckPath.value) truckPath.value.setMap(null)
  truckPath.value = new window.AMap.Polyline({
    path: fullRoutePoints.value,
    strokeColor: '#67C23A',
    strokeWeight: 6,
    strokeStyle: 'solid'
  })
  truckPath.value.setMap(map.value)
  // 小车标记
  if (truckMarker.value) truckMarker.value.setMap(null)
  truckMarker.value = new window.AMap.Text({
    text: '🚚',
    position: fullRoutePoints.value[0],
    style: {
      'font-size': '40px',
      'font-weight': 'bold',
      'color': '#67C23A',
      'background-color': 'white',
      'border-radius': '50%',
      'border': '3px solid #67C23A',
      'padding': '8px',
      'box-shadow': '0 4px 12px rgba(0,0,0,0.3)'
    },
    offset: new window.AMap.Pixel(-30, -30)
  })
  truckMarker.value.setMap(map.value)
  // 动画
  let pointIndex = 0
  let stationIdx = 0
  updateTruckInfo(stationIdx)
  const stationPoints = deliveryRoute.map(([lng, lat]) => `${lng},${lat}`)
  // 计算每次前进点数，使全程约10秒走完，且比原来快2倍
  const totalPoints = fullRoutePoints.value.length
  const totalDuration = 10000 // 10秒
  const interval = 20 // 每20ms移动一次
  const steps = Math.ceil(totalDuration / interval)
  const stepPoints = Math.max(1, Math.ceil(totalPoints / steps)) * 2 // 快2倍
  let lastFetchIndex = -20;
  const move = () => {
    if (!isTruckMoving.value) return
    if (pointIndex >= fullRoutePoints.value.length) {
      isTruckMoving.value = false
      updateTruckInfo(deliveryRoute.length - 1)
      ElMessage.success('配送完成！')
      return
    }
    // 判断是否到达下一个站点
    const curStr = fullRoutePoints.value[pointIndex].join(',')
    if (stationIdx < stationPoints.length - 1 && curStr === stationPoints[stationIdx + 1]) {
      stationIdx++
      updateTruckInfo(stationIdx)
    }
    truckMarker.value.setPosition(fullRoutePoints.value[pointIndex])
    // 每隔20步请求一次地区
    if (pointIndex - lastFetchIndex >= 20) {
      const [lng, lat] = fullRoutePoints.value[pointIndex]
      fetchLocationName(lng, lat)
      lastFetchIndex = pointIndex
    }
    pointIndex += stepPoints
    setTimeout(move, interval)
  }
  move()
  ElMessage.success('开始配送！')
}

// 停止货车配送
function stopTruckDelivery() {
  if (truckMarker.value) {
    truckMarker.value.setMap(null)
    truckMarker.value = null
  }
  if (truckPath.value) {
    truckPath.value.setMap(null)
    truckPath.value = null
  }
  isTruckMoving.value = false
  ElMessage.info('配送已停止')
}

async function fetchLocationName(lng, lat) {
  const url = `https://restapi.amap.com/v3/geocode/regeo?location=${lng},${lat}&key=${AMAP_KEY}&radius=1000&extensions=base`
  const res = await fetch(url)
  const data = await res.json()
  if (data.status === '1' && data.regeocode) {
    // 优先显示区县、城市、省份
    const addr = data.regeocode.addressComponent
    let name = ''
    if (addr.city && typeof addr.city === 'string') name += addr.city
    else if (addr.province) name += addr.province
    if (addr.district) name += addr.district
    if (addr.township) name += addr.township
    currentLocationName.value = name || '未知地区'
  } else {
    currentLocationName.value = '未知地区'
  }
}

onMounted(async () => {
  try {
    await loadAMapScript()
    
    // 创建地图实例
    map.value = new window.AMap.Map('amap-container', {
      center: [116.397428, 39.90923],
      zoom: 5
    })

    // 添加站点标记
    addStationMarkers()
    
  } catch (e) {
    console.error('地图加载失败:', e)
    mapError.value = true
  }
})
</script>

<template>
  <div class="tracking-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索地点..."
          class="search-input"
          @keyup.enter="apiSearch"
        >
          <template #append>
            <el-button @click="apiSearch" type="primary">
              <i class="el-icon-search"></i>
            </el-button>
          </template>
        </el-input>
        
        <!-- 搜索结果 -->
        <div v-if="showSearchResults && searchResults.length > 0" class="search-results">
          <div
            v-for="place in searchResults"
            :key="place.id"
            class="search-result-item"
            @click="selectSearchResult(place)"
          >
            <div class="result-icon">📍</div>
            <div class="result-info">
              <div class="result-name">{{ place.name }}</div>
              <div class="result-address">{{ place.address }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="tool-buttons">
        <el-button @click="getCurrentLocation" type="success" size="small">
          <i class="el-icon-location"></i> 定位
        </el-button>
        <el-button @click="startMeasuring" type="warning" size="small">
          <i class="el-icon-ruler"></i> 测距
        </el-button>
        <el-button @click="clearMeasuring" type="info" size="small">
          <i class="el-icon-delete"></i> 清除
        </el-button>
        <el-button @click="addCustomMarker" type="primary" size="small">
          <i class="el-icon-plus"></i> 添加标记
        </el-button>
        <el-button @click="simpleSearchTest" type="warning" size="small">
          <i class="el-icon-connection"></i> API测试
        </el-button>
        <el-button @click="startTruckDelivery" type="success" size="small" :disabled="isTruckMoving">
          <i class="el-icon-van"></i> 开始配送
        </el-button>
        <el-button @click="stopTruckDelivery" type="danger" size="small" :disabled="!isTruckMoving">
          <i class="el-icon-close"></i> 停止配送
        </el-button>
      </div>
      <!-- 新增：配送进度信息 -->
      <div v-if="isTruckMoving || nextStationName !== ''" class="truck-info-panel" style="margin-top:18px; padding:12px 18px; background:#f7fafd; border-radius:10px; box-shadow:0 2px 8px rgba(60,120,200,0.06); font-size:15px; color:#333;">
        <div><b>下一站：</b>{{ nextStationName }}</div>
        <div v-if="estimatedDistance > 0"><b>预计路程：</b>{{ estimatedDistance.toFixed(2) }} 公里</div>
        <div v-if="estimatedTime > 0"><b>预计时间：</b>{{ (estimatedTime*60).toFixed(0) }} 分钟</div>
        <div v-if="currentLocationName"><b>当前位置：</b>{{ currentLocationName }}</div>
      </div>
    </div>

    <!-- 地图容器 -->
    <div id="amap-container" v-if="!mapError"></div>
    <div v-else class="map-error">
      <div class="error-content">
        <div class="error-icon">🗺️</div>
        <h3>地图加载失败</h3>
        <p>请检查网络连接和API密钥设置</p>
        <el-button type="primary" @click="location.reload()">重新加载</el-button>
      </div>
    </div>

    <!-- 添加自定义标记对话框 -->
    <el-dialog v-model="showMarkerForm" title="添加自定义标记" width="400px">
      <el-form :model="newMarker" label-width="80px">
        <el-form-item label="标记名称" required>
          <el-input v-model="newMarker.name" placeholder="请输入标记名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="newMarker.description"
            type="textarea"
            :rows="3"
            placeholder="请输入标记描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showMarkerForm = false">取消</el-button>
        <el-button type="primary" @click="confirmAddMarker">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.tracking-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.toolbar {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  min-width: 300px;
}

.search-section {
  margin-bottom: 15px;
}

.search-input {
  width: 100%;
}

.search-results {
  margin-top: 10px;
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: white;
}

.search-result-item {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s;
}

.search-result-item:hover {
  background-color: #f5f7fa;
}

.search-result-item:last-child {
  border-bottom: none;
}

.result-icon {
  font-size: 20px;
  margin-right: 10px;
}

.result-info {
  flex: 1;
}

.result-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.result-address {
  font-size: 12px;
  color: #909399;
}

.tool-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

#amap-container {
  width: 100%;
  height: 100%;
  border-radius: 0;
  box-shadow: none;
  margin: 0;
}

.map-error {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.error-content {
  text-align: center;
  padding: 40px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  backdrop-filter: blur(10px);
}

.error-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.error-content h3 {
  font-size: 24px;
  margin-bottom: 10px;
}

.error-content p {
  font-size: 16px;
  margin-bottom: 20px;
  opacity: 0.9;
}

@media (max-width: 768px) {
  .toolbar {
    left: 10px;
    right: 10px;
    min-width: auto;
  }
  
  .tool-buttons {
    justify-content: center;
  }
}
</style>